package com.zr.task.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.annotation.security.PermitAll;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletResponse;

import com.zr.common.annotation.Anonymous;
import com.zr.common.constant.SimpleDateFormatConstants;
import com.zr.task.domain.EimTaskImgBase64;
import com.zr.task.domain.EimTaskLog;
import com.zr.task.service.IEimTaskCommandScheduleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.zr.common.annotation.Log;
import com.zr.common.core.controller.BaseController;
import com.zr.common.core.domain.AjaxResult;
import com.zr.common.enums.BusinessType;
import com.zr.task.domain.EimTaskSampling;
import com.zr.task.service.IEimTaskSamplingService;
import com.zr.common.utils.poi.ExcelUtil;
import com.zr.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 采样任务Controller
 * 
 * @author zhaojunqi
 * @date 2022-10-21
 */
@MultipartConfig
@RestController
@RequestMapping("/eim/sampling")
@CrossOrigin
public class EimTaskSamplingController extends BaseController
{
    @Autowired
    private IEimTaskSamplingService eimTaskSamplingService;


    /**
     * 完成环境采样任务
     */
    @PostMapping("/end")
    @Anonymous
    @Transactional
    public void end(MultipartFile file, EimTaskSampling eimTaskSampling, @RequestParam("personId") String personId, @RequestParam("type") String type) throws IOException {

        //文件夹地址
        String directoryName = "D:\\img\\" +
                eimTaskSampling.getIdCard() +
                "_" +
                SimpleDateFormatConstants.sfImg.format(eimTaskSampling.getSamplingTime()) +
                "\\";
        //设置图片名称
        String imgName = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //将文件夹地址存储至数据库
        eimTaskSampling.setSamplingImg(directoryName);
        //更新环境采样详情单
        eimTaskSamplingService.updateEimTaskSamplingByIdCard(eimTaskSampling);
        //更新父单订单状态
        eimTaskSamplingService.updateEimTaskCommandSchedule(eimTaskSampling.getPid());
        //增加完成日志
        EimTaskLog eimTaskLog = new EimTaskLog();
        eimTaskLog.setTaskId(Long.parseLong(eimTaskSampling.getPid()));
        eimTaskLog.setTaskType(type);
        eimTaskLog.setTaskStatus("3");
        eimTaskLog.setTaskUserId(personId);
        eimTaskLog.setCreateTime(new Date());
        eimTaskSamplingService.addTaskTranshipmentLog(eimTaskLog);

        //创建文件夹存储图片
        File f = new File(directoryName + imgName);
        if(!f.exists()){
            f.mkdirs();
        }
        file.transferTo(f);
    }

    /**
     * 获取指定的环境采样任务详情的图片
     * @param eimTaskSampling 环境采样任务
     * @return
     * @throws IOException
     */
    @PostMapping("/getImg")
    @PermitAll
    public AjaxResult getImg(EimTaskSampling eimTaskSampling) throws IOException {
        EimTaskSampling sampling = eimTaskSamplingService.selectEimTaskSamplingById(eimTaskSampling.getId());
        AjaxResult ajaxResult = new AjaxResult();
        //表示一个文件路径
        File file = new File(sampling.getSamplingImg());
        //用数组把文件夹下的文件存起来
        File[] files = file.listFiles();
        //获取指定文件夹内图片的base64码集合
        List<EimTaskImgBase64> imgList = new ArrayList<>();
        for(int i = 0;i<files.length;i++){
            EimTaskImgBase64 eimTaskImgBase64 = new EimTaskImgBase64();
            eimTaskImgBase64.setImgName(files[i].getName());
            eimTaskImgBase64.setImgUrl(ImageToBase64(files[i].getPath()));
            imgList.add(eimTaskImgBase64);
        }
        //设置存放照片base64的list的key值为img
        ajaxResult.put("img", imgList);
        return ajaxResult;
    }

    /**
     * 图片转base64码
     * @param imgPath 图片路径
     * @return
     * @throws IOException
     */
    private String ImageToBase64(String imgPath) throws IOException {
        String base64Str = "";
        FileInputStream inputStream = null;
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            inputStream = new FileInputStream(imgPath);
            int available = inputStream.available();
            byte[] bytes = new byte[available];
            inputStream.read(bytes);
            base64Str = encoder.encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            inputStream.close();
        }
        return base64Str;
    }

    /**
     * 查询采样任务列表
     */
    @PreAuthorize("@ss.hasPermi('eim:sampling:list')")
    @GetMapping("/list")
    public TableDataInfo list(EimTaskSampling eimTaskSampling)
    {
        startPage();
        List<EimTaskSampling> list = eimTaskSamplingService.selectEimTaskSamplingList(eimTaskSampling);
        return getDataTable(list);
    }

    /**
     * 导出采样任务列表
     */
    @PreAuthorize("@ss.hasPermi('eim:sampling:export')")
    @Log(title = "采样任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EimTaskSampling eimTaskSampling)
    {
        List<EimTaskSampling> list = eimTaskSamplingService.selectEimTaskSamplingList(eimTaskSampling);
        ExcelUtil<EimTaskSampling> util = new ExcelUtil<EimTaskSampling>(EimTaskSampling.class);
        util.exportExcel(response, list, "采样任务数据");
    }

    /**
     * 获取采样任务详细信息
     */
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(@RequestParam("id") Long id)
    {
        return AjaxResult.success(eimTaskSamplingService.selectEimTaskSamplingById(id));
    }

    /**
     * 新增采样任务
     */
    @PreAuthorize("@ss.hasPermi('eim:sampling:add')")
    @Log(title = "采样任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody EimTaskSampling eimTaskSampling)
    {
        return toAjax(eimTaskSamplingService.insertEimTaskSampling(eimTaskSampling));
    }

    /**
     * 修改采样任务
     */
    @PreAuthorize("@ss.hasPermi('eim:sampling:edit')")
    @Log(title = "采样任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EimTaskSampling eimTaskSampling)
    {
        return toAjax(eimTaskSamplingService.updateEimTaskSampling(eimTaskSampling));
    }

    /**
     * 删除采样任务
     */
    @PreAuthorize("@ss.hasPermi('eim:sampling:remove')")
    @Log(title = "采样任务", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(eimTaskSamplingService.deleteEimTaskSamplingByIds(ids));
    }

    /**
     * 创建子任务
     * 需求：APP
     */
    @PostMapping("/addByLeader")
    public AjaxResult addByLeader(EimTaskSampling eimTaskSampling)
    {
        eimTaskSamplingService.insertEimTaskSampling(eimTaskSampling);
        return AjaxResult.success(eimTaskSampling);
    }
}
